package com.unswift;

import java.awt.AWTEvent;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Properties;

import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cache.MemoryCache;
import com.unswift.constant.QuickConstant;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.FileUtils;
import com.unswift.utils.FreemarkerUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.window.MainWindow;
import com.unswift.window.dialog.HelpDialog;

@Api(value="快速开发应用启动类", author="unswift", date="2023-06-17", version="1.0.0")
public class QuickApplication {

	private static String basePath;
	private static String jarPath;
	public static MemoryCache cache=MemoryCache.getInstance();
	
	@ApiMethod(value="启动main方法", params=@ApiField("启动参数"))
	public static void main(String[] args) {
		try {
			String runningMethod=ObjectUtils.init(System.getProperty("runningMethod"), "java");
			cache.set("runningMethod", runningMethod);
			basePath=getConfigPath(runningMethod);
			cache.set("basePath", basePath);
			Properties conf=new Properties();
			conf.load(new InputStreamReader(new FileInputStream(basePath+QuickConstant.CONF_FILE_PATH), "UTF-8"));
			cache.set("conf", conf);
			ExceptionUtils.loadingMessageXml(Thread.currentThread().getContextClassLoader().getResourceAsStream("quick-exception.xml"), "cloud-exception.xml");
			
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			System.out.println("字体："+getConfig(QuickConstant.CONF_FONT_FAMILY));
            initGlobalFont(new Font(getConfig(QuickConstant.CONF_FONT_FAMILY), Integer.parseInt(getConfig(QuickConstant.CONF_FONT_STYLE)), Integer.parseInt(getConfig(QuickConstant.CONF_FONT_SIZE))));//Courier New
            setConfig(QuickConstant.CONF_JRE_PATH, System.getProperty("user.dir")+"\\jre");
            cache.set(QuickConstant.CACHE_WINDOW, new MainWindow());
            String init=getConfig(QuickConstant.CONF_INIT);
            if(ObjectUtils.isEmpty(init) || !"true".equals(init)) {
            	new HelpDialog(getWindow(), "开发者序", "tools-describe");
            	setConfig(QuickConstant.CONF_INIT, "true");
            }
            String templatePath=QuickApplication.getBasePath()+"/template";
    		FreemarkerUtils.setConfiguration(templatePath);
			setAllowClose(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@ApiMethod(value="获取前端可选择的架构数组，来自conf.properties", returns=@ApiField("可选择的前端架构数组"))
	public static String[] getProjectWebFrameworks(){
		Properties conf=cache.get("conf");
		return conf.getProperty(QuickConstant.CONF_CREATE_PROJECT_WEB_FRAMEWORKS).split("\\,");
	}
	
	@ApiMethod(value="获取创建项目时所有的微服务数组", returns=@ApiField("微服务数组"))
	public static String[] getProjectServers(){
		Properties conf=cache.get("conf");
		return conf.getProperty(QuickConstant.CONF_CREATE_PROJECT_SERVERS).split("\\,");
	}
	
	@ApiMethod(value="获取使用的开发工具数组", returns=@ApiField("开发工具数组"))
	public static String[] getDevelopTools(){
		Properties conf=cache.get("conf");
		return conf.getProperty(QuickConstant.CONF_CREATE_PROJECT_DEVELOP_TOOLS).split("\\,");
	}
	
	@ApiMethod(value="获取创建项目的说明", returns=@ApiField("说明"))
	public static String getCreateProjectDescribe(){
		return FileUtils.reader(new File(basePath+"\\help\\create-project-describe.txt"), "UTF-8");
	}
	
	@ApiMethod(value="获取开发工具欢迎语", returns=@ApiField("开发工具欢迎语"))
	public static String getDescribe(String type){
		return FileUtils.reader(new File(basePath+"\\help\\"+type+".txt"), "UTF-8");
	}
	
	@ApiMethod(value="获取工具的window窗口对象", returns=@ApiField("window窗口对象，继承JFrame类"))
	public static MainWindow getWindow(){
		return cache.get(QuickConstant.CACHE_WINDOW);
	}
	
	@ApiMethod(value="当前窗口是否允许关闭", returns=@ApiField("是否允许关闭，true：不允许关闭，false：允许关闭"))
	public static boolean isAllowClose(){
		return cache.get(QuickConstant.CACHE_ALLOW_CLOSED);
	}
	
	@ApiMethod(value="设置窗口是否允许关闭", params=@ApiField("是否允许关闭，true：不允许关闭，false：允许关闭"))
	public static void setAllowClose(boolean allowClosed){
		System.out.println("设置了："+allowClosed);
		cache.set(QuickConstant.CACHE_ALLOW_CLOSED, allowClosed);
	}
	
	public static void setExeTime(String time){
		JLabel exeTime=cache.get(QuickConstant.CACHE_EXE_TIME);
		exeTime.setText("耗时："+time);
	}
	
	public static void setExeTimeLable(JLabel exeTime){
		cache.set(QuickConstant.CACHE_EXE_TIME_LABEL, exeTime);
	}
	
	public static String getBasePath() {
		return basePath;
	}
	
	public static String getJarPath() {
		return jarPath;
	}
	
	public static String getConfig(String key){
		Properties conf=cache.get("conf");
		return conf.getProperty(key);
	}
	
	public static void setConfig(String key, String value){
		Properties conf=cache.get("conf");
		conf.setProperty(key, value);
		try {
			conf.store(new OutputStreamWriter(new FileOutputStream(basePath+QuickConstant.CONF_FILE_PATH), "UTF-8"), "store key="+key+",value="+value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String getConfigPath(String runningMethod){
		if("exe".equals(runningMethod)){
			return Thread.currentThread().getContextClassLoader().getResource("").getFile();
		}else{
			String file=QuickApplication.class.getResource("").getFile();
			int index=file.indexOf(".jar!");
			if(index!=-1){
				file=file.substring(0, index);
				file=file.replace("file:", "");
				jarPath=(file+".jar").substring(1);
				index=file.lastIndexOf("/");
				if(index==-1){
					index=file.lastIndexOf("\\");
				}
				file=file.substring(0, index+1);
			}else{
				index=file.lastIndexOf("/com/unswift");
				if(index==-1){
					index=file.lastIndexOf("\\com\\unswift");
				}
				file=file.substring(0, index+1);
			}
			return file;
		}
	}
	
	private static void initGlobalFont(Font font) {
		FontUIResource fontRes = new FontUIResource(font);
		for (Enumeration<Object> keys = UIManager.getDefaults().keys();keys.hasMoreElements(); ) {
			Object key = keys.nextElement();
			Object value = UIManager.get(key);
			if (value instanceof FontUIResource) {
				UIManager.put(key, fontRes);
			}
		}
		Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
			public void eventDispatched(AWTEvent event) {
				KeyEvent e=(KeyEvent)event;
				if (e.getID() == KeyEvent.KEY_PRESSED) {
					if(e.getKeyCode()==KeyEvent.VK_F12){
						
					}
				}
			}
		}, AWTEvent.KEY_EVENT_MASK);
	}
}
